﻿using Framework.Components;
using System.Diagnostics;
using Framework.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace CmdService
{
    static class Program
    {

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        public static int Main(string[] args)
        {
            var exePath = Process.GetCurrentProcess().MainModule.FileName; //启动程序路径
            var curPath = Path.GetDirectoryName(exePath);


            // 设置日志路径
            string logPath = curPath + "/logs/";
            Log.Instance.Handler = new Log.FileLogHandler(logPath, "log");
            Log.Info("程序路径: " + Path.GetFullPath("."));
            Log.Info("启动参数: " + StringUtils.ToString(args));
            Log.Info("日志路径: " + Path.GetFullPath(logPath));

            // 默认参数处理
            if (args == null || args.Length <= 0)
            {
                //args = new string[] {
                //    "-r", "C:\\Users\\HLART-4\\Desktop\\tcluster_leizou\\server_all.bat", "",
                //    "-t",
                //    "-s", "C:\\Users\\HLART-4\\Desktop\\tcluster_leizou\\server_stop_all.bat" };

                args = new string[] {
                    "-r", "start.bat", "",
                    "-s", "stop.bat", "",
                    "-t",
                };
            }

            // 程序解析处理
            CmdProgresss.Instance.Init(args);
            CmdProgresss.Instance.Logger.Handler = new Log.FileLogHandler(logPath, "rlog");

#if DEBUG
            // 判断是否是测试程序
            if (CmdProgresss.Instance.ContainsKey("-t"))
            {
                try
                {
                    // 测试启动关闭
                    CmdProgresss.Instance.Start();
                    Thread.Sleep(5 * 1000);
                    CmdProgresss.Instance.Stop();
                }
                catch(Exception e)
                {
                    Log.Error("测试错误: ", e);
                }
                Process.GetCurrentProcess().Kill();
                return 0;
            }
#endif

            // 启动服务
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new CmdService()
            };
            ServiceBase.Run(ServicesToRun);
            return 0;
        }
    }
}
